<template>
  <div class="dashboard">
    <h1 class="page-title neon-text">CMDB 大数据仪表盘</h1>
    
    <!-- 核心统计卡片 -->
    <el-row :gutter="20" style="margin-bottom: 20px">
      <el-col :span="6">
        <div class="stat-card stat-card-primary">
          <div class="stat-icon">
            <el-icon :size="40"><Monitor /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">主机总数</div>
            <div class="stat-number">{{ stats.hostCount }}</div>
            <div class="stat-detail">
              <span class="stat-success">{{ stats.onlineCount }} 在线</span>
              <span class="stat-danger">{{ stats.offlineCount }} 离线</span>
            </div>
          </div>
        </div>
      </el-col>
      
      <el-col :span="6">
        <div class="stat-card stat-card-secondary">
          <div class="stat-icon">
            <el-icon :size="40"><Folder /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">项目数量</div>
            <div class="stat-number">{{ stats.projectCount }}</div>
            <div class="stat-detail">
              <span>管理中的项目</span>
            </div>
          </div>
        </div>
      </el-col>
      
      <el-col :span="6">
        <div class="stat-card stat-card-warning">
          <div class="stat-icon">
            <el-icon :size="40"><Setting /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">环境数量</div>
            <div class="stat-number">{{ stats.envCount }}</div>
            <div class="stat-detail">
              <span>多环境部署</span>
            </div>
          </div>
        </div>
      </el-col>
      
      <el-col :span="6">
        <div class="stat-card stat-card-danger">
          <div class="stat-icon">
            <el-icon :size="40"><User /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">用户数量</div>
            <div class="stat-number">{{ stats.userCount }}</div>
            <div class="stat-detail">
              <span>系统用户</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" style="margin-bottom: 20px">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <el-icon><TrendCharts /></el-icon>
              <span>主机状态分布</span>
            </div>
          </template>
          <div ref="statusChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <el-icon><PieChart /></el-icon>
              <span>环境分布统计</span>
            </div>
          </template>
          <div ref="envChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-bottom: 20px">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <el-icon><Histogram /></el-icon>
              <span>主机组分布</span>
            </div>
          </template>
          <div ref="groupChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <el-icon><DataLine /></el-icon>
              <span>项目主机分布</span>
            </div>
          </template>
          <div ref="projectChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主机列表 -->
    <el-card class="recent-hosts">
      <template #header>
        <div class="card-header">
          <div>
            <el-icon><List /></el-icon>
            <span>主机资源列表</span>
          </div>
          <el-button type="primary" size="small" @click="$router.push('/host')">
            查看全部
          </el-button>
        </div>
      </template>
      
      <el-table :data="recentHosts" style="width: 100%">
        <el-table-column prop="hostname" label="主机名" min-width="150" />
        <el-table-column prop="ip_address" label="IP地址" min-width="150" />
        <el-table-column prop="port" label="端口" width="80" />
        <el-table-column prop="project_name" label="项目" min-width="120" />
        <el-table-column prop="environment_name" label="环境" min-width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" effect="dark">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="openTerminal(row.id)"
            >
              <el-icon><Connection /></el-icon>
              连接
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { hostAPI, projectAPI, environmentAPI, userAPI, hostGroupAPI } from '@/api'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

const router = useRouter()

const stats = ref({
  hostCount: 0,
  projectCount: 0,
  envCount: 0,
  userCount: 0,
  onlineCount: 0,
  offlineCount: 0
})

const recentHosts = ref([])
const statusChartRef = ref(null)
const envChartRef = ref(null)
const groupChartRef = ref(null)
const projectChartRef = ref(null)

let statusChart = null
let envChart = null
let groupChart = null
let projectChart = null

const loadStats = async () => {
  try {
    const [hosts, projects, envs, users, groups] = await Promise.all([
      hostAPI.getList(),
      projectAPI.getList(),
      environmentAPI.getList(),
      userAPI.getList(),
      hostGroupAPI.getList()
    ])
    
    const hostList = hosts.results || hosts
    const onlineHosts = hostList.filter(h => h.status === 'online')
    const offlineHosts = hostList.filter(h => h.status === 'offline')
    
    stats.value = {
      hostCount: hostList.length,
      projectCount: (projects.results || projects).length,
      envCount: (envs.results || envs).length,
      userCount: (users.results || users).length,
      onlineCount: onlineHosts.length,
      offlineCount: offlineHosts.length
    }
    
    recentHosts.value = hostList.slice(0, 10)
    
    await nextTick()
    initCharts(hostList, projects.results || projects, envs.results || envs, groups.results || groups)
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  }
}

const initCharts = (hosts, projects, envs, groups) => {
  // 主机状态分布图
  if (statusChartRef.value) {
    statusChart = echarts.init(statusChartRef.value)
    const statusData = [
      { value: hosts.filter(h => h.status === 'online').length, name: '在线' },
      { value: hosts.filter(h => h.status === 'offline').length, name: '离线' },
      { value: hosts.filter(h => h.status === 'maintenance').length, name: '维护中' }
    ]
    
    statusChart.setOption({
      tooltip: { trigger: 'item' },
      legend: {
        orient: 'vertical',
        left: 'left',
        textStyle: { color: '#e0e0e0' }
      },
      series: [{
        name: '主机状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#0a0e27',
          borderWidth: 2
        },
        label: { color: '#e0e0e0' },
        emphasis: {
          label: { show: true, fontSize: 16, fontWeight: 'bold' }
        },
        data: statusData,
        color: ['#00ff9f', '#8892b0', '#ffbe0b']
      }]
    })
  }
  
  // 环境分布图
  if (envChartRef.value) {
    envChart = echarts.init(envChartRef.value)
    const envData = envs.map(env => ({
      value: hosts.filter(h => h.environment === env.id).length,
      name: env.name
    }))
    
    envChart.setOption({
      tooltip: { trigger: 'item' },
      legend: {
        bottom: '5%',
        left: 'center',
        textStyle: { color: '#e0e0e0' }
      },
      series: [{
        name: '环境分布',
        type: 'pie',
        radius: '60%',
        data: envData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 255, 159, 0.5)'
          }
        },
        label: { color: '#e0e0e0' },
        color: ['#00ff9f', '#00d4ff', '#ffbe0b', '#ff006e']
      }]
    })
  }
  
  // 主机组分布图
  if (groupChartRef.value) {
    groupChart = echarts.init(groupChartRef.value)
    const groupNames = groups.map(g => g.name)
    const groupData = groups.map(g => hosts.filter(h => h.host_group === g.id).length)
    
    groupChart.setOption({
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: {
        type: 'category',
        data: groupNames,
        axisLabel: { color: '#e0e0e0' },
        axisLine: { lineStyle: { color: '#00ff9f' } }
      },
      yAxis: {
        type: 'value',
        axisLabel: { color: '#e0e0e0' },
        axisLine: { lineStyle: { color: '#00ff9f' } },
        splitLine: { lineStyle: { color: 'rgba(0, 255, 159, 0.1)' } }
      },
      series: [{
        name: '主机数量',
        type: 'bar',
        data: groupData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#00ff9f' },
            { offset: 1, color: '#00d4ff' }
          ]),
          borderRadius: [5, 5, 0, 0]
        },
        emphasis: { itemStyle: { color: '#00ff9f' } }
      }]
    })
  }
  
  // 项目主机分布图
  if (projectChartRef.value) {
    projectChart = echarts.init(projectChartRef.value)
    const projectNames = projects.map(p => p.name)
    const projectData = projects.map(p => hosts.filter(h => h.project === p.id).length)
    
    projectChart.setOption({
      tooltip: { trigger: 'axis' },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: projectNames,
        axisLabel: { color: '#e0e0e0' },
        axisLine: { lineStyle: { color: '#00ff9f' } }
      },
      yAxis: {
        type: 'value',
        axisLabel: { color: '#e0e0e0' },
        axisLine: { lineStyle: { color: '#00ff9f' } },
        splitLine: { lineStyle: { color: 'rgba(0, 255, 159, 0.1)' } }
      },
      series: [{
        name: '主机数量',
        type: 'line',
        data: projectData,
        smooth: true,
        lineStyle: { color: '#00ff9f', width: 3 },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(0, 255, 159, 0.5)' },
            { offset: 1, color: 'rgba(0, 255, 159, 0.1)' }
          ])
        },
        itemStyle: { color: '#00ff9f' }
      }]
    })
  }
}

const getStatusType = (status) => {
  const map = {
    'online': 'success',
    'offline': 'info',
    'maintenance': 'warning'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    'online': '在线',
    'offline': '离线',
    'maintenance': '维护中'
  }
  return map[status] || status
}

const openTerminal = (hostId) => {
  router.push(`/terminal/${hostId}`)
}

onMounted(() => {
  loadStats()
  
  // 响应式调整图表大小
  window.addEventListener('resize', () => {
    statusChart?.resize()
    envChart?.resize()
    groupChart?.resize()
    projectChart?.resize()
  })
})

onUnmounted(() => {
  statusChart?.dispose()
  envChart?.dispose()
  groupChart?.dispose()
  projectChart?.dispose()
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.page-title {
  font-size: 36px;
  margin-bottom: 30px;
  color: var(--cyber-primary);
  font-family: 'Courier New', monospace;
  letter-spacing: 4px;
  text-align: center;
  text-transform: uppercase;
}

/* 统计卡片样式 */
.stat-card {
  background: linear-gradient(135deg, var(--cyber-bg-secondary) 0%, #1a2040 100%);
  border: 2px solid var(--cyber-primary);
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 0 20px rgba(0, 255, 159, 0.3);
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(0, 255, 159, 0.2), transparent);
  transition: left 0.5s;
}

.stat-card:hover::before {
  left: 100%;
}

.stat-card:hover {
  transform: translateY(-8px) scale(1.02);
  box-shadow: 0 0 40px rgba(0, 255, 159, 0.6);
}

.stat-card-primary {
  border-color: var(--cyber-primary);
}

.stat-card-secondary {
  border-color: var(--cyber-secondary);
}

.stat-card-warning {
  border-color: var(--cyber-warning);
}

.stat-card-danger {
  border-color: var(--cyber-accent);
}

.stat-icon {
  width: 70px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 255, 159, 0.1);
  border-radius: 50%;
  color: var(--cyber-primary);
  font-size: 40px;
}

.stat-card-secondary .stat-icon {
  background: rgba(0, 212, 255, 0.1);
  color: var(--cyber-secondary);
}

.stat-card-warning .stat-icon {
  background: rgba(255, 190, 11, 0.1);
  color: var(--cyber-warning);
}

.stat-card-danger .stat-icon {
  background: rgba(255, 0, 110, 0.1);
  color: var(--cyber-accent);
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: var(--cyber-text-dim);
  margin-bottom: 8px;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.stat-number {
  font-size: 42px;
  font-weight: bold;
  color: var(--cyber-primary);
  text-shadow: 0 0 10px var(--cyber-primary);
  font-family: 'Courier New', monospace;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-card-secondary .stat-number {
  color: var(--cyber-secondary);
  text-shadow: 0 0 10px var(--cyber-secondary);
}

.stat-card-warning .stat-number {
  color: var(--cyber-warning);
  text-shadow: 0 0 10px var(--cyber-warning);
}

.stat-card-danger .stat-number {
  color: var(--cyber-accent);
  text-shadow: 0 0 10px var(--cyber-accent);
}

.stat-detail {
  font-size: 12px;
  color: var(--cyber-text-dim);
  display: flex;
  gap: 15px;
}

.stat-success {
  color: var(--cyber-primary);
}

.stat-danger {
  color: var(--cyber-accent);
}

/* 图表卡片 */
.chart-card {
  height: 100%;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: bold;
  font-size: 16px;
  color: var(--cyber-primary);
}

.card-header span {
  text-transform: uppercase;
  letter-spacing: 1px;
}

/* 主机列表 */
.recent-hosts {
  margin-top: 20px;
}

.recent-hosts .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.recent-hosts .card-header > div {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
